#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

void mywrite(int wfd)
{
	char message[1024] = {0};
	int i = 1;
	while (1)
	{
		// 自定义设置写入的内容
		snprintf(message, sizeof(message), "send a message to father, mypid is : %d, i = %d\n", getpid(), i);
		++i;
		write(wfd, message, strlen(message));

        // 方便观察
        sleep(1);
	}
}

void myread(int rfd)
{
	char message[1024] = {0};

	while (1)
	{
        // 读
		ssize_t n = read(rfd, message, sizeof(message) - 1);
		message[n] = '\0';
		printf("%s", message);

        // 方便观察
        sleep(1);
	}
}

int main()
{
	// 子进程写，父进程读
	int pipefd[2] = {0};
	int pret = pipe(pipefd);
	if (pret < 0)
	{
		printf("create pipe fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
		return errno;
	}
	pid_t id = fork();
	if (id == 0)
	{
		// 子进程关闭读端
		close(pipefd[0]);
		mywrite(pipefd[1]);
		close(pipefd[1]);
		exit(0);
	}
	// 父进程关闭写端
	close(pipefd[1]);

	myread(pipefd[0]);

	close(pipefd[0]);
	// 等待，防止僵尸
	wait(NULL);

	return 0;
}
